package com.qf.dao.Impl;

import com.qf.dao.UserDao;
import com.qf.dto.UserDto;
import com.qf.pojo.User;
import com.qf.util.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.Connection;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {

    private QueryRunner queryRunner = new QueryRunner();

    @Override
    public User login(UserDto userDto) {
        try {
            DBUtils.begin();
            String sql = "select * from t_user where username = ? and password = ?";
            User user = queryRunner.query(DBUtils.getConnection(),
                    sql,
                    new BeanHandler<>(User.class),
                    userDto.getUsername(),userDto.getPassword());
            DBUtils.commit();
            return user;
        } catch (SQLException e) {
            e.printStackTrace();
            DBUtils.rollback();
        }
        return null;
    }

    @Override
    public int insert(UserDto userDto) {
        try {
            DBUtils.begin();
            String sql = "insert into t_user (username, password) values (?, ?)";
            int result = queryRunner.update(DBUtils.getConnection(),
                    sql,
                    userDto.getUsername(), userDto.getPassword());
            DBUtils.commit();
            return result;
        } catch (SQLException e) {
            e.printStackTrace();
            DBUtils.rollback();
        }
        return -1;
    }

    @Override
    public User findById(Integer uid) {
        //获取连接
        Connection connection = DBUtils.getConnection();

        //sql
        String sql = "select * from t_user where uid = ?";

        //调用方法
        User user = null;

        try {
            user = queryRunner.query(connection, sql, new BeanHandler<>(User.class),
                    uid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        return user;
    }
}
